# app.py
import tornado.web
import logging.handlers
from tornado.options import define, options
from config import LOGS_DIR
from utils.db_util import CreateEngine

file_handler = logging.handlers.TimedRotatingFileHandler(
    LOGS_DIR, when='midnight', backupCount=7, encoding='utf8'
)
console_handler = logging.StreamHandler()
logging.basicConfig(
    format="%(asctime)s %(levelname)s %(message)s",
    level=logging.INFO,
    datefmt="%Y-%m-%d %H:%M:%S",
    handlers=[file_handler, console_handler],
)


class Application(tornado.web.Application):
    def __init__(self):
        from handlers.urls import URLS
        from utils.model_util import init_model

        # 初始化所有依赖项并存入 settings
        self.settings = {
            "model": init_model()
        }
        self.db_session = self.get_sql_session("db_session")
        self.standardized_session = self.get_sql_session("standardized_session")
        super().__init__(URLS, **self.settings)
        logging.info("Application initialized with all dependencies")

    @staticmethod
    def get_sql_session(method="db_session"):
        engine = CreateEngine()
        return engine.get_engine(method)


if __name__ == "__main__":
    define("port", default=8001, type=int)
    tornado.options.parse_command_line()
    app = Application()
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()
